package com.zyw.auth.service.impl;

import com.zyw.auth.common.IConstants;
import com.zyw.auth.common.ShiroAuthHelper;
import com.zyw.auth.service.CaptchaService;
import com.zyw.common.util.CaptchaImageUtil;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class CaptchaServiceImpl implements CaptchaService {


    @Override
    public Map<String, String> generateImageAndUuid() {
        Map<String,String> res = new HashMap<>();
        Object[] captchaInfos = CaptchaImageUtil.getCaptchaInfos();
        if (null == captchaInfos) {
            return null;
        }
        String code = (String) captchaInfos[0];
        Session session = ShiroAuthHelper.getCurrentSession();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        if (null != session) {
            session.setAttribute(IConstants.LOGIN_UUID_SESSION_KEY, uuid);
            session.setAttribute(IConstants.LOGIN_CAPTCHA_SESSION_KEY, code);
        }
        byte[] bytes = (byte[]) captchaInfos[1];
        BASE64Encoder encoder = new BASE64Encoder();
        res.put("image",encoder.encode(bytes));
        res.put("uuid",uuid);
        return res;
    }
}
